package yiran.stock.lister;

import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import yiran.stock.Stock;
import yiran.stock.StockCommand;
import yiran.stock.StockManager;
import yiran.stock.gui.StockGUI;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class EventListener implements Listener {
    private final Material guiOpenItem;
    private final Map<UUID, Long> lastPressTime = new HashMap<>();
    private final StockManager stockManager;
    private final Stock plugin;

    public EventListener(Material guiOpenItem, StockManager stockManager, Stock plugin) {
        this.guiOpenItem = guiOpenItem;
        this.stockManager = stockManager;
        this.plugin = plugin;
    }
    
    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        if (event.getAction() != Action.RIGHT_CLICK_AIR && 
            event.getAction() != Action.RIGHT_CLICK_BLOCK) {
            return;
        }

        ItemStack item = player.getInventory().getItemInMainHand();
        if (item == null || item.getType() != guiOpenItem) {
            return;
        }

        long now = System.currentTimeMillis();
        if (now - lastPressTime.getOrDefault(player.getUniqueId(), 0L) > 500) {
            lastPressTime.put(player.getUniqueId(), now);
            openStockGui(player);
        }
    }

    private void openStockGui(Player player) {
        StockGUI gui = new StockGUI(player, stockManager, plugin);
        StockCommand.openGUIs.put(player.getUniqueId(), gui);
        gui.open();
    }
}
